<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" title="经费类型管理">
        管理评审费经费类型，包括科研经费和其他经费的标准配置。
      </n-card>
    </div>
    <n-card :bordered="false" title="经费类型列表" class="mt-4">
      <n-space vertical :size="16">
        <!-- 搜索栏 -->
        <n-space justify="space-between">
          <n-space>
            <n-input
              v-model:value="searchParams.keyword"
              placeholder="请输入经费类型名称"
              style="width: 300px"
              clearable
            />
            <n-select
              v-model:value="searchParams.status"
              placeholder="状态筛选"
              :options="statusOptions"
              style="width: 150px"
              clearable
            />
            <n-button type="primary" @click="handleSearch">
              <template #icon>
                <n-icon>
                  <SearchOutline />
                </n-icon>
              </template>
              搜索
            </n-button>
            <n-button @click="handleReset">重置</n-button>
          </n-space>
          <n-button type="primary" @click="handleAdd">
            <template #icon>
              <n-icon>
                <AddOutline />
              </n-icon>
            </template>
            新增经费类型
          </n-button>
        </n-space>

        <!-- 数据表格 -->
        <n-data-table
          :columns="columns"
          :data="tableData"
          :loading="loading"
          :pagination="pagination"
          :row-key="rowKey"
          @update:page="handlePageChange"
        />
      </n-space>
    </n-card>

    <!-- 新增/编辑弹窗 -->
    <n-modal
      v-model:show="showModal"
      :title="modalTitle"
      preset="card"
      style="width: 600px"
      :mask-closable="false"
    >
      <n-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-placement="left"
        :label-width="120"
        require-mark-placement="right-hanging"
      >
        <n-form-item label="经费类型名称" path="name">
          <n-input v-model:value="formData.name" placeholder="请输入经费类型名称" style="width: 100%" />
        </n-form-item>
        <n-form-item label="经费类型编码" path="code">
          <n-input v-model:value="formData.code" placeholder="请输入经费类型编码" style="width: 100%" />
        </n-form-item>
        <n-form-item label="经费类型" path="fundingType">
          <n-select
            v-model:value="formData.fundingType"
            :options="fundingTypeOptions"
            placeholder="请选择经费类型"
            style="width: 100%"
          />
        </n-form-item>
        <n-form-item label="专家级别" path="expertLevel">
          <n-select
            v-model:value="formData.expertLevel"
            :options="expertLevelOptions"
            placeholder="请选择专家级别"
            style="width: 100%"
            @update:value="handleExpertLevelChange"
          />
        </n-form-item>
        <n-form-item :label="`${selectedExpertLevelName}最小金额`" path="minAmount" v-if="formData.expertLevel">
          <n-input-number
            v-model:value="formData.minAmount"
            :placeholder="`请输入${selectedExpertLevelName}最小金额`"
            :min="0"
            :precision="2"
            style="width: 100%"
          >
            <template #suffix>元</template>
          </n-input-number>
        </n-form-item>
        <n-form-item :label="`${selectedExpertLevelName}最大金额`" path="maxAmount" v-if="formData.expertLevel">
          <n-input-number
            v-model:value="formData.maxAmount"
            :placeholder="`请输入${selectedExpertLevelName}最大金额`"
            :min="0"
            :precision="2"
            style="width: 100%"
          >
            <template #suffix>元</template>
          </n-input-number>
        </n-form-item>
        <n-form-item label="状态" path="status">
          <n-radio-group v-model:value="formData.status">
            <n-space>
              <n-radio :value="1">启用</n-radio>
              <n-radio :value="0">禁用</n-radio>
            </n-space>
          </n-radio-group>
        </n-form-item>
        <n-form-item label="排序" path="sort">
          <n-input-number
            v-model:value="formData.sort"
            placeholder="请输入排序值"
            :min="0"
            :max="999"
            style="width: 100%"
          />
        </n-form-item>
        <n-form-item label="备注" path="remark">
          <n-input
            v-model:value="formData.remark"
            type="textarea"
            placeholder="请输入备注信息"
            :rows="2"
          />
        </n-form-item>
      </n-form>
      <template #footer>
        <n-space justify="end">
          <n-button @click="showModal = false">取消</n-button>
          <n-button type="primary" :loading="submitLoading" @click="handleSubmit">
            确定
          </n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, h, computed } from 'vue';
import { useMessage, useDialog, NSwitch } from 'naive-ui';
import {
  SearchOutline,
  AddOutline,
  CreateOutline,
  TrashOutline,
} from '@vicons/ionicons5';
import { createIndexColumn } from '@/utils/tableUtil';

const message = useMessage();
const dialog = useDialog();

// 搜索参数
const searchParams = reactive({
  keyword: '',
  status: null as number | null,
});

// 状态选项
const statusOptions = [
  { label: '启用', value: 1 },
  { label: '禁用', value: 0 },
];

// 专家级别选项
const expertLevelOptions = [
  { label: '院士、全国知名专家', value: 'academician' },
  { label: '高级专业技术职称专家', value: 'senior' },
  { label: '其他专家', value: 'other' },
];

// 专家级别名称映射
const expertLevelNameMap = {
  academician: '院士',
  senior: '高级专家',
  other: '其他专家'
};

// 经费类型选项
const fundingTypeOptions = [
  { label: '科研经费', value: 'research' },
  { label: '其他经费', value: 'other' },
];

// 表格数据
const loading = ref(false);
const tableData = ref<any[]>([]);
const pagination = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageCount: 0,
  onChange: (page: number) => {
    pagination.page = page;
    loadData();
  },
  onUpdatePageSize: (pageSize: number) => {
    pagination.pageSize = pageSize;
    pagination.page = 1;
    loadData();
  },
});

// 表格列定义
const columns = computed(() => [
  createIndexColumn({
    currentPage: pagination.page,
    pageSize: pagination.pageSize,
  }),
  { title: '经费类型名', key: 'name', width: 150 },
  { title: '编码', key: 'code', width: 120 },
  { title: '经费类型', key: 'fundingType', width: 120 },
  { title: '专家级别', key: 'expertLevel', width: 150 },
  { title: '金额范围', key: 'amountRange', width: 150 },
  {
    title: '状态',
    key: 'status',
    width: 100,
    render: (row: any) => {
      return h('div', { style: 'display: flex; align-items: center; gap: 8px;' }, [
        h(NSwitch, {
          value: row.status === 1,
          onUpdateValue: (value: boolean) => {
            row.status = value ? 1 : 0;
            console.log('状态切换:', row.id, value ? 1 : 0);
          }
        }),
        h('span', { style: 'font-size: 12px;' }, row.status === 1 ? '启用' : '禁用')
      ]);
    }
  },
  { title: '排序', key: 'sort', width: 100 },
  { title: '创建时间', key: 'createTime', width: 180 },
  {
    title: '操作',
    key: 'actions',
    width: 150,
    render: (row: any) => {
      return h('div', [
        h(
          'n-button',
          {
            size: 'small',
            type: 'primary',
            ghost: true,
            onClick: () => handleEdit(row),
            style: 'margin-right: 8px',
          },
          { default: () => '编辑' }
        ),
        h(
          'n-button',
          {
            size: 'small',
            type: 'error',
            ghost: true,
            onClick: () => handleDelete(row),
          },
          { default: () => '删除' }
        ),
      ]);
    },
  },
]);

// 表单相关
const showModal = ref(false);
const modalTitle = ref('新增经费类型');
const submitLoading = ref(false);
const formRef = ref();
const formData = reactive({
  id: '',
  name: '',
  code: '',
  fundingType: '',
  expertLevel: '',
  minAmount: 0,
  maxAmount: 0,
  status: 1,
  sort: 0,
  remark: '',
});

const rules = {
  name: {
    required: true,
    message: '请输入经费类型名称',
    trigger: 'blur',
  },
  code: {
    required: true,
    message: '请输入经费类型编码',
    trigger: 'blur',
  },
};

// 计算属性
const selectedExpertLevelName = computed(() => {
  if (!formData.expertLevel) return '';
  
  // 如果expertLevel是中文名称，直接返回
  if (typeof formData.expertLevel === 'string' && formData.expertLevel.includes('专家')) {
    return formData.expertLevel;
  }
  
  // 如果是英文值，则从映射中获取
  return expertLevelNameMap[formData.expertLevel as keyof typeof expertLevelNameMap] || '';
});

// 方法
const rowKey = (row: any) => row.id;

const handleExpertLevelChange = (value: string) => {
  // 当专家级别改变时，重置金额字段
  formData.minAmount = 0;
  formData.maxAmount = 0;
};

const loadData = () => {
  loading.value = true;
  // 模拟API调用
  setTimeout(() => {
    tableData.value = [
      {
        id: '1',
        name: '科研项目评审费',
        code: 'RESEARCH_REVIEW',
        fundingType: '科研经费',
        expertLevel: '院士、全国知名专家',
        amountRange: '2250-3600元',
        status: 1,
        sort: 1,
        createTime: '2024-01-15 10:30:00',
        remark: '科研项目评审费标准',
      },
      {
        id: '2',
        name: '科研项目评审费',
        code: 'RESEARCH_REVIEW',
        fundingType: '科研经费',
        expertLevel: '高级专业技术职称专家',
        amountRange: '1500-2400元',
        status: 1,
        sort: 2,
        createTime: '2024-01-15 10:30:00',
        remark: '科研项目评审费标准',
      },
      {
        id: '3',
        name: '科研项目评审费',
        code: 'RESEARCH_REVIEW',
        fundingType: '科研经费',
        expertLevel: '其他专家',
        amountRange: '900-1500元',
        status: 1,
        sort: 3,
        createTime: '2024-01-15 10:30:00',
        remark: '科研项目评审费标准',
      },
      {
        id: '4',
        name: '其他项目评审费',
        code: 'OTHER_REVIEW',
        fundingType: '其他经费',
        expertLevel: '院士、全国知名专家',
        amountRange: '500-800元',
        status: 1,
        sort: 4,
        createTime: '2024-01-15 10:30:00',
        remark: '其他项目评审费标准',
      },
      {
        id: '5',
        name: '其他项目评审费',
        code: 'OTHER_REVIEW',
        fundingType: '其他经费',
        expertLevel: '高级专业技术职称专家',
        amountRange: '500-800元',
        status: 1,
        sort: 5,
        createTime: '2024-01-15 10:30:00',
        remark: '其他项目评审费标准',
      },
      {
        id: '6',
        name: '其他项目评审费',
        code: 'OTHER_REVIEW',
        fundingType: '其他经费',
        expertLevel: '其他专家',
        amountRange: '300-500元',
        status: 1,
        sort: 6,
        createTime: '2024-01-15 10:30:00',
        remark: '其他项目评审费标准',
      },
    ];
    pagination.pageCount = 1;
    loading.value = false;
  }, 500);
};

const handleSearch = () => {
  pagination.page = 1;
  loadData();
};

const handleReset = () => {
  searchParams.keyword = '';
  searchParams.status = null;
  pagination.page = 1;
  loadData();
};

const handlePageChange = (page: number) => {
  pagination.page = page;
  loadData();
};

const handleAdd = () => {
  modalTitle.value = '新增经费类型';
  Object.assign(formData, {
    id: '',
    name: '',
    code: '',
    fundingType: '',
    expertLevel: '',
    minAmount: 0,
    maxAmount: 0,
    status: 1,
    sort: 0,
    remark: '',
  });
  showModal.value = true;
};

const handleEdit = (row: any) => {
  modalTitle.value = '编辑经费类型';
  Object.assign(formData, row);
  showModal.value = true;
};

const handleDelete = (row: any) => {
  dialog.warning({
    title: '确认删除',
    content: `确定要删除经费类型"${row.name}"吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      message.success('删除成功');
      loadData();
    },
  });
};

const handleSubmit = () => {
  formRef.value?.validate((errors: any) => {
    if (!errors) {
      submitLoading.value = true;
      setTimeout(() => {
        message.success(formData.id ? '更新成功' : '创建成功');
        showModal.value = false;
        submitLoading.value = false;
        loadData();
      }, 1000);
    }
  });
};

onMounted(() => {
  loadData();
});
</script>

<style scoped>
.n-layout-page-header {
  background: #fff;
  padding: 16px;
  border-radius: 6px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}
</style> 